<template>
	<view class="content">
		<NAVBAR-CPN></NAVBAR-CPN>
		<actionNavbar v-if="cityInfo.lat" @add-city="handleAddCity" @cancel-preview="handleCancelPreview">
		</actionNavbar>
		<HeadTools v-else></HeadTools>
		<button @tap="requestLocationPermission" v-if="!locationWeather.temp">获取天气信息</button>
		<!--  -->
		<view class="viewContent" v-if="locationWeather.temp">
			<view class="scrollArea">
				<infoCpn :locationWeather="locationWeather" :locationInfo="locationInfo">
				</infoCpn>
			</view>
			<view v-if="allCityArr.length > 0">
				<swiper class="swiper" circular :indicator-dots="indicatorDots" :duration="duration"
					indicator-color="rgba(0, 0, 0, .3)" indicator-active-color="#ffffff" @change="swiperChange">
					<swiper-item v-for="(item,index) in allCityArr" :key="index">
						<view class="bottomList">
							<airTemperature :moreWeather='moreWeather'></airTemperature>
						</view>
					</swiper-item>
				</swiper>
			</view>


		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, toRefs } from 'vue'
	import HeadTools from "@/pages/component/headTools.vue";
	import infoCpn from "@/pages/index/component/infoCpn.vue";
	import airTemperature from "@/pages/index/component/airTemperature.vue";
	import actionNavbar from "@/pages/index/component/actionNavbar.vue";
	import { onMounted, onBeforeMount } from "vue";
	import request from '@/pages/utils/https.js';
	import { onLoad, onShow } from '@dcloudio/uni-app';
	const indicatorDots = ref(true)
	const duration = ref(500)
	const allCityArr = reactive([]);
	const maxminTemp = ref({
		tempMax: 0,
		tempMin: 0
	})
	let locationWeather = reactive({});
	let locationInfo = ref('')
	let moreWeather = reactive([]);
	let airInfo = ref({}) // 空气信息
	const cityInfo = ref({})
	const swiperChange = (e) => {
		let swipetIndex = e.target.current;
		try {
			// 获取城市数组
			const storedData = uni.getStorageSync('allCityArrayKey') || '[]';
			let dataArray = JSON.parse(storedData);
			let data = dataArray[swipetIndex]
			getCityInfo(data.lat, data.lon);
		} catch {
			console.log('暂无城市数组');
		}
		console.log(e.target.current);
	}
	onLoad((options) => {
		let infoData = {};
		try {
			// 检查是否存在 info 参数且非空
			if (options.info && typeof options.info === 'string') {
				infoData = JSON.parse(decodeURIComponent(options.info));
			}
		} catch (error) {
			infoData = { lat: null, lon: null }; // 示例默认值
		}
		// 更新响应式变量
		cityInfo.value = infoData;
		// 检查数据有效性后再调用接口
		if (cityInfo.value.lat && cityInfo.value.lon) {
			getCityInfo(cityInfo.value.lat, cityInfo.value.lon);
		} else {
		}

	});
	const handleAddCity = () => {
		updateCityArr(cityInfo.value)
		// allCityArr.push(cityInfo.value);
		cityInfo.value = {};
	}
	const handleCancelPreview = () => {
		uni.navigateBack({
			delta: 1
		})
	}
	// 在需要定位的页面或组件中
	const requestLocationPermission = async () => {
		// 1. 检查是否已有权限
		const { authSetting } = await uni.getSetting()
		// 2. 已授权直接获取定位
		if (authSetting['scope.userLocation']) {
			getLocation()
		} else {
			try {
				await uni.authorize({
					scope: 'scope.userLocation'
				})
				getLocation()
			} catch (error) {
				// 4. 用户拒绝后的处理
				uni.showModal({
					title: '死刑警告',
					content: '不授权定位无法使用核心功能',
					confirmText: '去授权',
					success: res => {
						res.confirm && openSetting()
					}
				})
				throw new Error('用户拒绝定位授权')
			}
		}
	}

	// 获取定位
	const getLocation = async () => {
		uni.getLocation({
			type: 'gcj02',
			success: function (res) {
				// 查询当前经纬度所属城市 （保留2位小数）
				const latNumber = parseFloat(res.latitude.toFixed(2));  // 24.57
				const lngNumber = parseFloat(res.longitude.toFixed(2));  // 118.24
				getCityInfo(latNumber, lngNumber);
			}, fail(e) {
				console.log(e);
			}
		});
	}

	// 跳转到设置页面（用户自己打开权限）
	const openSetting = () => {
		uni.openSetting({
			success: ({ authSetting }) => {
				authSetting['scope.userLocation'] && getLocation()
			}
		})
	}
	// 获取城市信息
	const getCityInfo = async (latNumber, lngNumber) => {
		try {
			const data = await request({
				url: 'https://geoapi.qweather.com/v2/city/lookup?location=' + lngNumber + ',' + latNumber,
				method: 'GET'
			});
			let locationID = data.location[0].id;
			locationInfo.value = data.location[0].name + ' - ' + data.location[0].adm2;
			updateCityArr(data.location[0])
			uni.setStorageSync('cityInfo', JSON.stringify(data.location[0]))
			getWeatherInfo(locationID);
			getAirInfo(locationID);
			getMoreWeather(locationID);
		} catch (error) {
			console.error('错误:', error);
		}
	}
	// 获取当前天气信息
	const getWeatherInfo = async (id) => {
		try {
			const data = await request({
				url: `https://devapi.qweather.com/v7/weather/now?location=${id}`,
				method: 'GET'
			});
			Object.assign(locationWeather, data.now)
			uni.setStorageSync('locationWeather', JSON.stringify(locationWeather))
		} catch (error) {
			console.error('错误:', error);
		}
	}
	// 获取近7天的天气数据
	const getMoreWeather = async (id) => {
		try {
			const data = await request({
				url: `https://devapi.qweather.com/v7/weather/7d?location=${id}`,
				method: 'GET'
			});
			let newArray = data.daily;
			// 创建带相对日期的新数组（不修改原数组）
			const dateArray = newArray.map(item => ({
				...item,
				relativeDate: formatRelativeDate(item.fxDate)
			}));

			moreWeather.splice(0, moreWeather.length, ...dateArray)
			Object.assign(locationWeather, {
				tempMax: moreWeather[0].tempMax,
				tempMin: moreWeather[0].tempMin
			});
			uni.setStorageSync('moreWeather', JSON.stringify(dateArray))
		} catch (error) {
			console.error('错误:', error);
		}
	}
	// 获取当地空气信息
	const getAirInfo = async (id) => {
		try {
			const data = await request({
				url: `https://devapi.qweather.com/v7/air/now?location=${id}`,
				method: 'GET'
			});
			locationWeather.aqi = data.now.aqi;
		} catch (error) {
			console.error('错误:', error);
		}
	}
	// 创建日期格式化函数
	const formatRelativeDate = (dateString) => {
		const weekDays = Object.freeze(['周日', '周一', '周二', '周三', '周四', '周五', '周六']);
		let cachedToday = null;

		// return (dateString) => {
		// 处理iOS日期格式
		const normalizedDate = dateString.replace(/-/g, '/');
		const targetDate = new Date(normalizedDate);
		targetDate.setHours(0, 0, 0, 0);

		// 缓存今天日期（每小时更新）
		const now = new Date();
		if (!cachedToday || now - cachedToday > 3600000) {
			cachedToday = new Date(now);
			cachedToday.setHours(0, 0, 0, 0);
		}

		// 计算天数差
		const diffDays = Math.floor((targetDate - cachedToday) / 86400000);

		// 最近三天处理
		if (diffDays === 0) return '今天';
		if (diffDays === 1) return '明天';
		if (diffDays === 2) return '后天';

		// 获取本地化星期（兼容时区）
		return weekDays[(targetDate.getDay() + 7) % 7];
		// };

	};
	// 取出所有城市数组添加新城市再存储（去重）
	const updateCityArr = async (newItem) => {
		try {
			// 1. 从本地存储获取原始数组
			const storedData = uni.getStorageSync('allCityArrayKey') || '[]';
			let dataArray = JSON.parse(storedData);

			// 2. 检查重复（假设用id字段判断唯一性）
			const isDuplicate = dataArray.some(item => item.id === newItem.id);

			// 3. 无重复则添加新项
			if (!isDuplicate) {
				dataArray.push(newItem); // 添加到数组开头
				// 可选：限制数组长度（如保留最近20条）
				// if (dataArray.length > 20) dataArray = dataArray.slice(0, 20);
			}

			// 4. 保存更新后的数组
			uni.setStorageSync('allCityArrayKey', JSON.stringify(dataArray));

			// 5. （可选）返回操作结果
			return {
				success: true,
				isNew: !isDuplicate,
				length: dataArray.length
			};
		} catch (error) {
			console.error('操作失败:', error);
			uni.showToast({
				title: '保存数据失败',
				icon: 'none'
			});
			return { success: false };
		}
	}
	// 获取所有城市数组
	const getMyAllCityArr = () => {
		try {
			const storedData = uni.getStorageSync('allCityArrayKey') || '[]';
			let dataArray = JSON.parse(storedData);
			allCityArr.splice(0, allCityArr.length, ...dataArray)
		} catch {
			console.log('暂无数组');
		}
	}
	// 检查是否有权限
	const checkSetting = async () => {
		const { authSetting } = await uni.getSetting()
		if (authSetting['scope.userLocation']) {
			getLocation()
		}
	}
	// 判断对象是否有值
	const isObjectEmpty = (obj) => {
		if (!obj) return true; // 处理 null/undefined
		return (
			typeof obj === 'object' &&
			!Array.isArray(obj) &&
			Object.keys(obj).length === 0
		);
	};

	onBeforeMount(() => {
		// console.log(isObjectEmpty(cityInfo.value));
		if (isObjectEmpty(cityInfo.value)) {
			checkSetting();
		}
	})
	onShow(() => {
		getMyAllCityArr()
	})
	onMounted(() => {
	});
</script>

<style scoped lang="scss">
	.content {
		min-height: 100vh;
		background-color: rgb(0, 0, 0);
		display: flex; // 启用死刑flex布局
		flex-direction: column; // 垂直方向处刑
		background-image: url("https://b0.bdstatic.com/b2dd05fdff9efa4bd1c651d0978cff8b.jpg");
		background-repeat: no-repeat;
		background-size: 100% 100%;

		.viewContent {
			flex: 1; // 占据剩余死亡空间
			padding: 24rpx;
			overflow: hidden; // 防止内容溢出

			display: flex; // 新增：启用 Flex 布局
			flex-direction: column; // 垂直方向

			.swiper {
				height: 500rpx;
			}

			.scrollArea {
				flex: 1; // 内容区域占据剩余空间（可滚动）
			}

			.bottomList {
				width: 100%;
				box-sizing: border-box;
			}
		}
	}
</style>